<template>
	<view>
		<u-navbar :isBack="true" title="商品详情" title-color="#101010"></u-navbar>
		<view style="position: relative;">
			<view v-if="goodsData.banner_images">
				<u-swiper :list="goodsData.banner_images" mode="number" indicator-pos="bottomRight" 
				height="600" border-radius="0"></u-swiper>
			</view>
		</view>
		<view style="padding: 24rpx 32rpx;">
			<view style="color: #000;font-size: 36rpx;font-weight: bold;">{{goodsData.title}}</view>
			<view style="font-size: 24rpx;display: flex;align-items: center;justify-content: space-between;">
				
				<view style="color: #FC7404;font-weight: bold;">
					<text>￥</text>
					<text style="font-size: 40rpx;">{{ goodsData.price }}</text>
					<text v-if="showMarket" style="color:#999999;font-weight: bold;padding-left: 20rpx;">原价：</text>
					<text v-if="showMarket" style="color:#999999;">￥</text>
					<text v-if="showMarket" style="font-size: 30rpx;text-decoration: line-through;
					color: #999999;font-weight:normal;">{{ goodsData.original_price }}</text>
				</view>
				<view style="color: #999999;">销量{{ goodsData.sales }}次</view>
			</view>
			<!-- <view style="color: #111111;font-size: 32rpx;font-weight: bold;margin-top: 16rpx;">家用中央空调清洗</view> -->
			<view v-if="goodsData.specList" v-for="(item, index) in goodsData.specList" :key="index" style="margin-right: 24rpx;color: #666666;display: flex;margin-top: 10rpx;">
				
				<text style="padding-left: 8rpx;color: #000;font-size: 30rpx;width: 150rpx;text-align: center;"> {{item.name}}： </text>
				<view style="width: 600rpx;display: flex;flex-wrap: wrap;">
					<view v-for="(item_c, index_c) in 3":key="index_c" v-if="item.id == item_c.pid" style="margin-right: 24rpx;color: #666666;">
						<!-- <view v-if="skuIds.indexOf(item_c.id)" ></view> -->
						<view :style="(skuIds.indexOf(item_c.id) > -1 ? 'border: #000 1rpx solid;' : 'border: #999999 1rpx solid;')+'width: 100rpx;border-radius: 10rpx;text-align: center;justify-content: center;align-items: center;'" @click="sku_choose(item_c)"> {{item_c.name}} </view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 保障标签 -->
		<view v-if="goodsData.tags">
			<u-gap height="24" bg-color="#F5F5F5"></u-gap>
			<view style="padding: 32rpx;display: flex;">
				<view style="font-weight: bold;">保障</view>
				<view style="flex: 1;font-size: 24rpx;display: flex;align-items: center;justify-content:flex-end;">
					<view v-for="(item, index) in goodsData.tags":key="index" style="margin-right: 24rpx;color: #666666;">
						<u-icon name="checkmark-circle" size="28" color="#0BB1EF"></u-icon>
						<text style="padding-left: 8rpx;"> {{item}} </text>
					</view>
				</view>
				<view>
					<u-icon name="arrow-right" color="#999999"></u-icon>
				</view>
			</view>
		</view>
		
		<u-gap height="24" bg-color="#F5F5F5"></u-gap>
		<!-- <view v-for="(item, index) in goodsData.banner_images":key="index" >
			<image :src="item" mode="widthFix" style="width: 750rpx;"></image>
		</view> -->
		<view style="padding: 24rpx;">
			<u-parse :html="goodsData.content"></u-parse>
		</view>
		<u-gap height="24" bg-color="#F5F5F5"></u-gap>
		<!-- 评价 -->
		<view style="padding: 32rpx;font-size: 28rpx;">
			<view style="display: flex;align-items: center;justify-content: space-between;">
				<view style="font-size: 32rpx;font-weight: bold;">评价(99+)</view>
				<view>
					<text style="color: #999999;padding-right: 8rpx;">查看全部</text>
					<u-icon name="arrow-right" color="#999999"></u-icon>
				</view>
			</view>
			<view v-for="(item, indexs) in goodsComment":key="index" style="margin-top: 24rpx;">
				<view style="display: flex;justify-content: space-between;">
					<view>
						<view style="display: flex;align-items: center;">
							<image src="@/static/logo.png" mode="widthFix" style="width: 64rpx;border-radius: 50%;"></image>
							<view style="margin-left: 8rpx;">
								<view style="font-size: 28rpx;">{{ item.nickname }}</view>
								<view>
									<u-rate :count="5" v-model="item.star" size="24" active-color="#FC7404"></u-rate>
								</view>
							</view>
						</view>
					</view>
					<view style="color: #CCCCCC;font-size: 24rpx;">{{ formatDateTime(new Date(item.createtime*1000), 'yyyy-MM') }}</view>
				</view>
				<view style="margin-top: 16rpx;"> {{item.content}} </view>
			</view>
		</view>
		<u-gap height="24" bg-color="#F5F5F5"></u-gap>
		<!-- 常见问题 -->
		<view style="padding: 32rpx;">
			<view style="font-size: 32rpx;font-weight: bold;">常见问题</view>
			<view v-for="(item, index) in goodsAsk":key="index" style="display: flex;margin-top: 24rpx;">
				<image src="@/static/logo.png" mode="widthFix" style="width: 48rpx;"></image>
				<view style="margin-left: 16rpx;flex: 1;">
					<view style="color: #333333;font-weight: bold;">{{ item.ask }}？</view>
					<view style="margin-top: 16rpx;">{{ item.content }}</view>
				</view>
			</view>
		</view>
		
		
		<view style="height: 108rpx;"></view>
		<!-- 底部按钮 -->
		<view style="position: fixed;bottom: 0;width: 100%;padding: 16rpx 32rpx;
		background: #fff;display: flex;justify-content: space-between;">
			<view>
				<!-- <image :src="configUrl.appurlImg + '/app/image-userinfo/icon_customerservice.png'" mode="widthFix" 
				style="width: 48rpx;"></image> -->
				<view style="font-size: 24rpx;color: #999999;">客服</view>
			</view>
			
			<view style="display: flex;align-items: center;" v-if="goodsData.price > 0">
				<!-- <view style="border: 1px solid #0BB1EF;border-radius: 16rpx;
				padding: 16rpx 52rpx;color: #0BB1EF;" @click="addCar">加入购物车</view> -->
				<view style="background: linear-gradient(to right, #5DCDF6, #0BB1EF);
				padding: 18rpx 66rpx;border-radius: 16rpx;margin-left: 24rpx;color: #fff;"
				@click="showSpecs = true">立即下单</view>
			</view>
			<view style="display: flex;align-items: center;" v-else>
				<view style="background: linear-gradient(to right, #5DCDF6, #0BB1EF);
				padding: 18rpx 170rpx;border-radius: 16rpx;margin-left: 24rpx;color: #fff;"
				@click="clickNoSubmit">填写需求 查看价格</view>
			</view>
		</view>
		
		<!-- 规格选择弹窗 -->
		<u-popup v-model="showSpecs" mode="bottom" border-radius="20">
			<view class="specs-popup">
				<!-- 商品信息区 -->
				<view class="product-info">
				  <image class="product-image" :src="currentProduct.image" mode="aspectFill"></image>
				  <view class="info-right">
					<view class="price">¥{{currentProduct.price}}</view>
					<!-- <view class="stock">库存: {{currentProduct.stock}}件</view> -->
					<view class="selected-specs">已选: {{getSelectedSpecsText()}}</view>
				  </view>
				</view>
				
				<!-- 规格选择区 -->
				<scroll-view scroll-y class="specs-scroll">
					<view class="specs-group" v-for="group in specsData" :key="group.id">
					  <view class="specs-title">{{group.title}}</view>
					  <view class="specs-items">
					    <view 
					      v-for="item in group.items" 
					      :key="item.id"
					      class="specs-item"
					      :class="{
					        'active': selectedSpecs[group.id] == item.id,
					        'disabled': !isSpecAvailable(group.id, item.id)
					      }"
					      @click="selectSpec(group.id, item.id)"
					    >
					      {{item.name}}
					    </view>
					  </view>
					</view>
				</scroll-view>
				
				
				<!-- 底部操作栏 -->
				<view class="footer">
					<view class="quantity">
						<text>数量</text>
						<u-number-box v-model="quantity" :min="1"></u-number-box>
					</view>
					<u-button type="error" @click="confirmSelection">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import configUrl  from '@/utils/config.js';
	import { request } from 'utils/request.js';
	// import { goodsApi } from '@/common/order.js';
	export default {
		name: "FinanceRegister",
		data() {
			return {
				showSpecs: false,
				quantity: 1,
				// 规格组数据
				specsData: [],
				// SKU价格数据
				skuPrices: [],
				// 当前选中的规格
				selectedSpecs: {},
				// 当前显示的商品信息
				currentProduct: {
					image: "",
					price: 0,
					// stock: 0,
					sku_text: "",
					id: 0
				},
					  
				goods_id: 0,
				goodsData: {},
				goodsComment: [],
				goodsAsk:[],
				skuChoose:[],
				skuIds:[],
				value: '20',
				topimg: '/app/sbanerbg.png',
				rectanglebg: '/app/Rectanglebg.png',
				showMarket:false
			};
		},
		onLoad(e){
			if(e.goods_id){
				this.goods_id = e.goods_id;
			}
			uni.setStorageSync("goodsSku","")
			uni.setStorageSync("goodsPrice","")
			this.infoDetails();
		},
		mounted() {
			// 初始化默认选中第一个可用规格
			// this.specsData.forEach(group => {
			// 	const availableItem = group.items.find(item => 
			// 		this.isSpecAvailable(group.title, item.name)
			// 	);
			// 	if (availableItem) {
			// 		this.selectSpec(group.title, availableItem.name);
			// 	}
			// });
		},
		methods: {
			infoDetails(){
				request.getWithToken({
					url: '/goods/goodsDetails',
					data: {goods_id : this.goods_id}
				}).then(res=>{
					console.log(res);
					let goodsData = res.data.goodsData;
					this.goodsData = goodsData;
					this.currentProduct.image = goodsData.image;
					this.currentProduct.price = goodsData.price;
					if(goodsData.is_sku == 1){
						this.fetchGoodsSpecs(goodsData.specsData);
						this.fetchGoodsSkuPrices(goodsData.skuPrices);
					}
					// this.actualDescImgs = res.data.orderData.desc_images;
				});
				// goodsApi.getGoodsDetails({goods_id: this.goods_id}).then(res => {
				// 	console.log(res)
				// 	this.goodsData = res.infoData;
				// 	this.goodsAsk = res.ask;
				// 	this.goodsComment = res.comment;
				// });
			},
			// 获取商品规格数据
			fetchGoodsSpecs(data) {
			    try {
					this.specsData = data.map(group => ({
						id: group.id,
						title: group.title,
						items: group.items.map(item => ({
							id: item.id,
							name: item.name
						}))
					}));
					// 初始化选中状态
					this.specsData.forEach(group => {
						this.$set(this.selectedSpecs, group.id, '');
					});
					console.log('specsData: ', this.specsData)
			    } catch (error) {
					console.error('获取规格数据失败:', error);
			    }
			},
			// 获取商品SKU价格数据
			fetchGoodsSkuPrices(data) {
			    try {
					this.skuPrices = data.map(item => ({
						...item,
						sku_ids: item.goods_sku_ids.split(',').map(id => parseInt(id))
					}));
			    } catch (error) {
					console.error('获取SKU价格数据失败:', error);
			    }
			},
			// 选择规格
			selectSpec(groupId, specId) {
				// 更新选中的规格
			    this.$set(this.selectedSpecs, groupId, specId);
			    
			    // 检查是否所有规格都已选择
			    const allSelected = Object.values(this.selectedSpecs).every(id => id !== '');
			    
				if (allSelected) {
					// 查找匹配的SKU
					const selectedIds = Object.values(this.selectedSpecs);
					const matchedSku = this.skuPrices.find(sku => 
						selectedIds.every(id => sku.sku_ids.includes(parseInt(id)))
					);
					if (matchedSku) {
						this.currentProduct = {
							image: matchedSku.image,
							price: matchedSku.price,
							id: matchedSku.id,
							// stock: matchedSku.stock || 0, // 假设stock字段存在
							sku_text: matchedSku.goods_sku_text
						};
					} else {
						// 没有匹配的SKU
						this.currentProduct = {
							image: "",
							price: 0,
							id: 0,
							// stock: 0,
							sku_text: ""
						};
					}
			    }
			},
			  
			  // 检查规格是否可选
			  isSpecAvailable(groupId, specId) {
			    // 如果已经选中，则可以直接切换
			    if (this.selectedSpecs[groupId] === specId) return true;
			    
			    // 临时保存当前选中的规格
			    const tempSelected = {...this.selectedSpecs};
			    tempSelected[groupId] = specId;
			    
			    // 获取已选的规格ID数组
			    const selectedIds = Object.values(tempSelected)
			      .filter(id => id !== '')
			      .map(id => parseInt(id));
			    
			    if (selectedIds.length === 0) return true;
			    
			    // 查找是否有SKU包含这些规格
			    return this.skuPrices.some(sku => {
			      // 检查SKU是否包含所有已选规格
			      return selectedIds.every(id => sku.sku_ids.includes(id));
			    });
			  },
			  
			  // 获取已选规格文本
			  getSelectedSpecsText() {
			    if (this.currentProduct.sku_text) {
			      return this.currentProduct.sku_text;
			    }
			    
			    const selected = [];
			    for (const groupId in this.selectedSpecs) {
			      if (this.selectedSpecs[groupId]) {
			        const group = this.specsData.find(g => g.id == groupId);
			        if (group) {
			          const item = group.items.find(i => i.id == this.selectedSpecs[groupId]);
			          if (item) {
			            selected.push(item.name);
			          }
			        }
			      }
			    }
			    
			    return selected.length > 0 ? selected.join(" ") : "请选择规格";
			  },
			    
			// 确认选择
			confirmSelection() {
				const allSelected = Object.values(this.selectedSpecs).every(item => item !== "");
				if (!allSelected) {
					uni.showToast({
						title: '请选择完整规格',
						icon: 'none'
					});
					return;
				}
				// uni.showToast({
				// 	title: `已选择: ${this.getSelectedSpecsText()}, 数量: ${this.quantity}`,
				// });
				this.showSpecs = false;
				this.clickSubmit();
			},
			sku_choose(c){
				var s = {
					id:c.id,
					pid:c.pid,
					name:c.name
				};
				this.skuIds = [];
				if(this.skuChoose.length > 0){
					var check = false;
					for(var i = 0; i < this.skuChoose.length; i++){
						
						if(this.skuChoose[i].pid == c.pid){
							this.skuChoose[i].name = c.name;
							this.skuChoose[i].id = c.id;
							check = true;
						}
					}
					if(!check){
						this.skuChoose.push(s)
					}
				}else{
					this.skuChoose.push(s)
				}
				var key = "";
				var pidList = [];
				for(var i = 0; i < this.skuChoose.length; i++){
					this.skuIds.push(this.skuChoose[i].id);
					pidList.push(this.skuChoose[i].pid)
					
				}
				// console.log(this.skuChoose)
				// console.log(this.skuIds)
				var txt_show = "";
				if(this.skuChoose.length == this.goodsData.specList.length){
					this.showMarket = true
					
					for(var t = 0; t < this.goodsData.specList.length; t++){
						if(txt_show != ""){
							txt_show +=",";
						}
						txt_show += this.goodsData.specList[t].name + ":" + this.skuChoose[pidList.indexOf(this.goodsData.specList[t].id)].name;
					}
					for(var k = 0; k < this.goodsData.specChildList.length; k++){
						if(this.skuIds.indexOf(this.goodsData.specChildList[k].id) > -1){
							// console.log(key)
							if(key != ""){
								key += '_'
							}
							key += this.skuChoose[this.skuIds.indexOf(this.goodsData.specChildList[k].id)].name;
						}
					}
					// console.log(key)
					this.goodsData.price = this.goodsData.skus[key].price;
					this.goodsData.mark_price = this.goodsData.skus[key].market_price;
					
					// console.log(txt_show)
					uni.setStorageSync("goodsSku",txt_show)
					uni.setStorageSync("goodsPrice",this.goodsData.skus[key].price)
				}else{
					this.showMarket = false
					txt_show = "";
					uni.setStorageSync("goodsSku","")
					uni.setStorageSync("goodsPrice","")
				}
			},
			
			
			// 页面条状
			toJump(e){
				uni.navigateTo({
					url: e,
				});
			},
			// 定价服务的提交
			clickSubmit(){
				// ${this.getSelectedSpecsText()}, 数量: ${this.quantity}
				console.log('currentProduct: ', this.currentProduct);
				console.log('quantity: ', this.quantity);
				uni.navigateTo({
					url: '/pages/goods/order?goods_id=' + this.goods_id + 
					'&price=' + this.currentProduct.price + '&skuprice_id=' + this.currentProduct.id + 
					'&sum=' + this.quantity + '&goods_sku_text=' + this.getSelectedSpecsText(),
				});
			},
			addCar(){
				if(this.skuChoose.length != this.goodsData.specList.length){
					uni.showToast({
					  title: '请选择规格！',
					  duration: 2000,
					  icon: 'none'
					});
					return
				}
				// console.log(this.skuChoose);
				// return;
				var key = "";
				var skutxt = "";
				if(this.skuChoose.length > 0){
					for(var s=0;s<this.skuChoose.length;s++){
						if(key != ""){
							key+="_";
						}
						key+=this.skuChoose[s].name;
					}
					skutxt=uni.getStorageSync("goodsSku");
				}
				
				goodsApi.addCar({goods_id: this.goods_id,key:key,sku:skutxt,price:uni.getStorageSync("goodsPrice")}).then(res => {
					uni.showToast({
					  title: '添加成功',
					  duration: 2000,
					  icon: 'none'
					});
				});
			},
			// 没有定价 - 跳转需求填写
			clickNoSubmit(){
				uni.navigateTo({
					url: '/pages/users/goods/demand?goods_id=' + this.goods_id,
				});
			},
			goout(){
				uni.navigateBack();
			},
			formatDateTime(date, format) {
				const o = {
					'M+': date.getMonth() + 1, // 月份
					'd+': date.getDate(), // 日
					'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
					'H+': date.getHours(), // 小时
					'm+': date.getMinutes(), // 分
					's+': date.getSeconds(), // 秒
					'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
					S: date.getMilliseconds(), // 毫秒
					a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
					A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
				};
				if (/(y+)/.test(format)) {
					format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				for (let k in o) {
					if (new RegExp('(' + k + ')').test(format)) {
					format = format.replace(
						RegExp.$1,
						RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
					);
					}
				}
				return format;
			},
		}
	};
</script>

<style>
	page {
		/* background: #FE8127 !important; */
	}
</style>
<style lang="scss" scoped>
	// @import "static/css/public-custom-form.scss";

	.circle {
	    display: inline-block; /* 行内元素块状化 */
	      width: 30px;
	      height: 30px;
	      font-size: 16px;
	      color: #ffffff; /* 字体颜色 */
	      text-align: center; /* 水平居中 */
	      line-height: 30px; /* 垂直居中 */
	      border-radius: 50%; /* 圆形 */
	      background: #000000; /* 背景色，也可以用url()方法引用背景图片 */
	}

	.confirm-btn {
	  margin: 32rpx;
	  // width: calc(100vw - 64rpx);
	  height: 100rpx;
	  line-height: 100rpx;
	  text-align: center;
	  color: #FC7404;
	  background-color: #fff;
	  // border-radius: 999px;
	  border-radius: 24rpx;
	  &:active {
		background-color: lighten(#fff, 10%);
	  }
	}
</style>

<style scoped>
.container {
  padding: 30rpx;
}

.specs-popup {
  padding: 30rpx;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.product-info {
  display: flex;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.product-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
}

.info-right {
  flex: 1;
  padding-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.price {
  font-size: 36rpx;
  color: #f40;
  font-weight: bold;
}

.stock {
  font-size: 24rpx;
  color: #999;
}

.selected-specs {
  font-size: 26rpx;
  color: #666;
}

.specs-scroll {
  flex: 1;
  margin-bottom: 20rpx;
}

.specs-group {
  margin-bottom: 30rpx;
}

.specs-title {
  font-size: 28rpx;
  margin-bottom: 20rpx;
  color: #333;
}

.specs-items {
  display: flex;
  flex-wrap: wrap;
}

.specs-item {
  padding: 10rpx 20rpx;
  margin-right: 20rpx;
  margin-bottom: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
}

.specs-item.active {
  border-color: #f40;
  color: #f40;
  background-color: #fff5f5;
}

.specs-item.disabled {
  color: #ccc;
  border-color: #eee;
  background-color: #f9f9f9;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.quantity {
  display: flex;
  align-items: center;
}

.quantity text {
  margin-right: 20rpx;
  font-size: 26rpx;
  color: #666;
}
</style>
